package com.sophialex.health.record.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Text;

public class TextCascade {

	public static <T> void cascade(final Combo combo, final Text text,
			final String comboPath, final T value, final boolean enable) {
		combo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				triger(combo, text,
						comboPath, value, enable);

			}
		});
		//触发初始可用/不可用
		triger(combo, text,
				comboPath, value, enable);
	}
	
	public static <T> void cascade(final Combo combo, Text text, String comboPath,
			T value) {
		cascade(combo, text, comboPath, value, true);
	}
	private static <T> void triger(final Combo combo, final Text text,
			final String comboPath, final T value, final boolean enable) {
		if(combo.getSelectionIndex() == -1){
			text.setEnabled(!enable);
			return ;
		}
		String s = combo.getItem(combo.getSelectionIndex());
		
		Object data = combo.getData(s);
		String[] dataPath = comboPath.split("\\.");
		String v = computeBeanPropValue(data, dataPath) + "";
		if (v.equals(value + "")){
			text.setEnabled(enable);
		}
		else{
			text.setText("");
			text.setEnabled(!enable);
		}
			
		
		
	}
	private static Object computeBeanPropValue(Object bean, String[] beanPath) {
		if (beanPath.length == 1) {
			Object value = null;
			value = getFieldValue(bean, beanPath[0]);

			return value;
		} else {
			Object o = getFieldValue(bean, beanPath[0]);
			String[] newPath = new String[beanPath.length - 1];
			System.arraycopy(beanPath, 1, newPath, 0, beanPath.length - 1);
			return computeBeanPropValue(o, newPath);
		}
	}

	private static Object getFieldValue(Object o, String fieldName) {
		Object value = null;
		Field f = null;
		try {
			f = o.getClass().getDeclaredField(fieldName);
			f.setAccessible(true);
			try {
				value = f.get(o);
			} catch (Exception e) {
				e.printStackTrace();
				
			}

		} catch (Exception e) {
			// e.printStackTrace();
			// 若没有名为fieldName的字段，那尝试调用getter
			String name = "get" + Character.toUpperCase(fieldName.charAt(0))
					+ fieldName.substring(1);
			// parent.out(name + "\r\n");
			Method getter = null;
			try {
				getter = o.getClass().getMethod(name);
			} catch (Exception e1) {
				e1.printStackTrace();
				
			}
			try {
				value = getter.invoke(o);
			} catch (Exception e1) {
				e1.printStackTrace();
				
			}
			return value;
		}

		return value;
	}
//	TextCascade.cascade(combo, text, "id",  2, true);//只有选择“女”文本框才可用
	

	
}
